// 混合WebSocket服务 - 保持WebSocket通信，使用localStorage替代存储API
// WebSocket通信：使用managerWebSocketService进行实时通信
// 数据存储：使用localStorage替代后端/service/chat接口

import { 
  localChatStorage, 
  type LocalChatMessage, 
  type LocalConversationState 
} from './localChatStorage';

// 导入managerWebSocketService而不是chatWebSocketService，避免重复连接
import { managerWebSocketService as originalWebSocketService } from './managerWebSocketService';

// 重新导出接口，保持兼容性 
export interface WebSocketMessage {
  type: 'message' | 'typing' | 'stopTyping' | 'heartbeat' | 'pong' | 'conversation_update' | 'error' | 'connection_closed';
  sender_id?: string;
  recipient_id?: string;
  content?: string;
  timestamp?: string;
  conversation_id?: string;
  message?: string; // for error messages
  uuid?: string;
}

export interface ChatMessage {
  id: string;
  sender_id: string;
  recipient_id: string;
  message_type: string;
  content: string;
  timestamp: string;
  status: string;
  conversation_id: string;
}

export interface ConversationState {
  _id: string;
  c_user_id: string;
  b_user_id: string;
  conversation_id: string;
  last_message_content: string;
  last_message_time: string;
  c_user_unread_count: number;
  b_user_unread_count: number;
  created_at: string;
  updated_at: string;
}

type MessageListener = (message: WebSocketMessage) => void;
type ConversationUpdateListener = (conversations: ConversationState[]) => void;

class HybridChatWebSocketService {
  constructor() {
    
    // 监听原始WebSocket服务的消息，同步到localStorage
    this.setupWebSocketMessageSync();
    
    // 监听localStorage变化以支持多标签页同步
    this.listenForStorageChanges();
    
    // 移除自动刷新会话列表，现在由managerWebSocketService统一管理连接
    console.log('LocalWebSocketService initialized (no auto-refresh)');
  }

  // 同步WebSocket消息到localStorage
  private setupWebSocketMessageSync() {
    // 监听原始WebSocket的消息
    originalWebSocketService.addMessageListener((wsMessage: WebSocketMessage) => {
      if (wsMessage.type === 'message' && wsMessage.sender_id && wsMessage.content) {
        // 将WebSocket消息同步保存到localStorage
        this.syncMessageToStorage(wsMessage);
      }
    });

    // 监听原始WebSocket的会话更新
    originalWebSocketService.addConversationUpdateListener((_conversations: ConversationState[]) => {
      // 这里我们优先使用localStorage的数据，不直接使用WebSocket的会话更新
    });
  }

  // 将WebSocket消息同步到localStorage
  private syncMessageToStorage(wsMessage: WebSocketMessage) {
    if (!wsMessage.sender_id || !wsMessage.recipient_id || !wsMessage.content) {
      return;
    }

    const currentUserId = this.getUserId();
    const conversationId = localChatStorage.generateConversationId(currentUserId, 
      wsMessage.sender_id === currentUserId ? wsMessage.recipient_id : wsMessage.sender_id);
    
    // 保存到localStorage
    localChatStorage.addMessage({
      sender_id: wsMessage.sender_id,
      recipient_id: wsMessage.recipient_id,
      message_type: 'text',
      content: wsMessage.content,
      timestamp: wsMessage.timestamp || new Date().toISOString(),
      status: wsMessage.sender_id === currentUserId ? 'sent' : 'received',
      conversation_id: conversationId
    });


  }

  // 监听localStorage变化以实现多标签页同步
  private listenForStorageChanges() {
    window.addEventListener('storage', (event) => {
      if (event.key === 'chat_conversations') {
        this.refreshConversations();
      }
    });
  }

  // ===============================================
  // 以下方法直接代理到原始WebSocket服务（保持实时通信）
  // ===============================================

  // 发送消息（使用原始WebSocket）
  sendMessage(message: WebSocketMessage) {
    originalWebSocketService.sendMessage(message);
    
    // 如果是聊天消息，同时保存到localStorage
    if (message.type === 'message' && message.content && message.recipient_id) {
      this.syncMessageToStorage(message);
    }
  }

  // 发送聊天消息给C端用户（使用原始WebSocket）
  sendChatMessage(recipientId: string, content: string) {
    // 通过原始WebSocket发送
    originalWebSocketService.sendChatMessage(recipientId, content);
    
    // 同时保存B端消息到localStorage
    const wsMessage: WebSocketMessage = {
      type: 'message',
      sender_id: this.getUserId(),
      recipient_id: recipientId,
      content: content,
      timestamp: new Date().toISOString()
    };
    
    this.syncMessageToStorage(wsMessage);
  }

  // 发送正在输入状态（使用原始WebSocket）
  sendTyping(recipientId: string) {
    originalWebSocketService.sendTyping(recipientId);
  }

  // 发送停止输入状态（使用原始WebSocket）
  sendStopTyping(recipientId: string) {
    originalWebSocketService.sendStopTyping(recipientId);
  }

  // 添加消息监听器（代理到原始WebSocket服务）
  addMessageListener(listener: MessageListener) {
    originalWebSocketService.addMessageListener(listener);
  }

  // 移除消息监听器（代理到原始WebSocket服务）
  removeMessageListener(listener: MessageListener) {
    originalWebSocketService.removeMessageListener(listener);
  }

  // 添加会话更新监听器（混合：localStorage + WebSocket）
  addConversationUpdateListener(listener: ConversationUpdateListener) {
    // 注册到localStorage服务
    localChatStorage.addConversationUpdateListener((localConversations) => {
      const convertedConversations = this.convertLocalToConversationState(localConversations);
      listener(convertedConversations);
    });
  }

  // 移除会话更新监听器
  removeConversationUpdateListener(_listener: ConversationUpdateListener) {
    // 这里可以添加更复杂的监听器管理逻辑
  }

  // 检查连接状态（使用原始WebSocket状态）
  isConnected(): boolean {
    return originalWebSocketService.isConnected();
  }

  // 获取用户ID（使用managerWebSocketService）
  getUserId(): string {
    return originalWebSocketService.getManagerId();
  }

  // 断开连接（现在由authService统一管理，这里只做清理工作）
  disconnect() {
    // 不直接断开底层WebSocket连接，因为连接管理现在由authService统一负责
    // 只清理本地状态和监听器
    console.log('LocalWebSocketService disconnect called (connection managed by authService)');
  }

  // ===============================================
  // localStorage相关方法（替代后端API）
  // ===============================================

  // 转换数据格式：LocalConversationState[] -> ConversationState[]
  private convertLocalToConversationState(localConversations: LocalConversationState[]): ConversationState[] {
    return localConversations.map(conv => ({
      _id: conv._id,
      c_user_id: conv.c_user_id,
      b_user_id: conv.b_user_id,
      // 移除conv_前缀，返回前端期望的格式
      conversation_id: conv.conversation_id.startsWith('conv_') ? conv.conversation_id.slice(5) : conv.conversation_id,
      last_message_content: conv.last_message_content,
      last_message_time: conv.last_message_time,
      c_user_unread_count: conv.c_user_unread_count,
      b_user_unread_count: conv.b_user_unread_count,
      created_at: conv.created_at,
      updated_at: conv.updated_at
    }));
  }

  // 转换数据格式：LocalChatMessage[] -> ChatMessage[]
  private convertLocalToChatMessage(localMessages: LocalChatMessage[]): ChatMessage[] {
    return localMessages.map(msg => ({
      id: msg.id,
      sender_id: msg.sender_id,
      recipient_id: msg.recipient_id,
      message_type: msg.message_type,
      content: msg.content,
      timestamp: msg.timestamp,
      status: msg.status,
      conversation_id: msg.conversation_id
    }));
  }

  // 获取会话列表（替代 GET /service/chat/conversations）
  async getConversations(): Promise<ConversationState[]> {
    try {
      const localConversations = localChatStorage.getConversations();
      const result = this.convertLocalToConversationState(localConversations);
      return result;
    } catch (error) {
      console.error('获取会话列表失败:', error);
      return [];
    }
  }

  // 获取会话消息历史（替代 GET /service/chat/conversations/${conversationId}/messages）
  async getConversationMessages(conversationId: string): Promise<ChatMessage[]> {
    try {
      // 转换conversationId格式：如果不带conv_前缀，自动添加
      const storageConversationId = conversationId.startsWith('conv_') ? conversationId : `conv_${conversationId}`;
      
      const localMessages = localChatStorage.getConversationMessages(storageConversationId);
      const result = this.convertLocalToChatMessage(localMessages);
      return result;
    } catch (error) {
      console.error('获取消息历史失败:', error);
      return [];
    }
  }

  // 标记会话为已读（替代 PUT /service/chat/conversations/${conversationId}/mark_read）
  async markConversationRead(conversationId: string): Promise<boolean> {
    try {
      // 转换conversationId格式：如果不带conv_前缀，自动添加
      const storageConversationId = conversationId.startsWith('conv_') ? conversationId : `conv_${conversationId}`;
      
      const success = localChatStorage.markConversationRead(storageConversationId, this.getUserId());
      
      if (success) {
        // 标记成功后刷新会话列表
        this.refreshConversations();
      }
      
      return success;
    } catch (error) {
      console.error('标记已读失败:', error);
      return false;
    }
  }

  // 刷新会话列表并通知监听器
  private async refreshConversations() {
    await this.getConversations();
    // 由于我们通过localChatStorage的监听器来通知，这里不需要手动通知
  }

  // ===============================================
  // 测试和调试功能
  // ===============================================
  
  // 模拟接收C端用户消息（用于测试）
  simulateIncomingMessage(senderId: string, content: string) {
    const conversationId = localChatStorage.generateConversationId(this.getUserId(), senderId);
    
    // 添加消息到本地存储
    const savedMessage = localChatStorage.addMessage({
      sender_id: senderId,
      recipient_id: this.getUserId(),
      message_type: 'text',
      content: content,
      timestamp: new Date().toISOString(),
      status: 'received',
      conversation_id: conversationId
    });

    // 模拟WebSocket消息接收 - 使用原始服务的sendMessage来触发监听器
    setTimeout(() => {
      // 直接调用原始服务的消息发送方法来模拟接收
      // 这会触发所有已注册的消息监听器
      try {
        // 由于这是模拟，我们直接通过localStorage的同步机制来实现
        // localStorage的变化会自动触发页面更新
        window.dispatchEvent(new StorageEvent('storage', {
          key: 'chat_messages',
          newValue: JSON.stringify(localChatStorage.getStats()),
          url: window.location.href
        }));
      } catch (error) {

      }
    }, 100);

    return savedMessage;
  }

  // 创建测试数据
  createTestData() {
    // 使用真实的用户ID创建测试消息
    const testMessages = [
      { senderId: 'yang_dandan', content: '你好，我想了解一下理财产品' },
      { senderId: 'hu_ying', content: '请问有什么推荐的投资方案吗？' },
      { senderId: 'yang_dandan', content: '我的风险偏好比较保守，希望有稳健型产品' },
      { senderId: 'hu_ying', content: '最近市场行情怎么样？有什么好的机会吗？' },
      { senderId: 'yang_dandan', content: '我看了你推荐的产品，很感兴趣' }
    ];

    testMessages.forEach((msg, index) => {
      setTimeout(() => {
        this.simulateIncomingMessage(msg.senderId, msg.content);
        
        // 模拟B端回复
        if (index % 2 === 0) {
          setTimeout(() => {
            this.simulateBEndReply(msg.senderId, `感谢您的咨询！针对您的需求，我为您推荐几款适合的理财产品。`);
          }, 500);
        }
      }, index * 1500); // 错开时间发送
    });
  }

  // 模拟B端回复
  private simulateBEndReply(recipientId: string, content: string) {
    const conversationId = localChatStorage.generateConversationId('B_Admin001', recipientId);
    
    // 添加B端消息到本地存储
    const savedMessage = localChatStorage.addMessage({
      sender_id: 'B_Admin001',
      recipient_id: recipientId,
      message_type: 'text',
      content: content,
      timestamp: new Date().toISOString(),
      status: 'sent',
      conversation_id: conversationId
    });

    return savedMessage;
  }

  // 获取服务状态
  getServiceStatus() {
    return {
      connected: this.isConnected(),
      userId: this.getUserId(),
      websocketService: 'managerWebSocketService',
      storageService: 'localStorage',
      storageStats: localChatStorage.getStats()
    };
  }
}

// 导出单例服务
export const localChatWebSocketService = new HybridChatWebSocketService();

// 开发调试工具（仅在开发环境下暴露到全局）
if (process.env.NODE_ENV === 'development') {
  (window as any).localChatWebSocketService = localChatWebSocketService;
} 